var Skink; if (!Skink) Skink = {};

if (!Skink.Sys) Skink.Sys = {};

Skink.Sys.getVersion = function() {
    var appXML = air.NativeApplication.nativeApplication.applicationDescriptor
    var domParser = new DOMParser();
    appXML = domParser.parseFromString(appXML, "text/xml");
    var version = appXML.getElementsByTagName("version")[0].firstChild.nodeValue;
    return version;
};

Skink.Sys.initUserAgentString = function() {
    window.htmlLoader.userAgent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Skink/' + Skink.Sys.getVersion();
    // air.URLRequestDefaults.userAgent = air.HTMLLoader.userAgent
    air.trace(window.htmlLoader.userAgent)
    return window.htmlLoader.userAgent
};

Skink.Sys.getUserAgent = function() {
    return window.htmlLoader.userAgent
};

Skink.Sys.getClipboardText = function() {
    if (air.Clipboard.generalClipboard.hasFormat("text/plain")) {
        var text = air.Clipboard.generalClipboard.getData("text/plain");
        return text;
    } else {
        return '';
    }
}

Skink.Sys.setClipboardText = function(text) {
    Skink.dump('Copying "' + text + '" to clipboard');
    air.Clipboard.generalClipboard.clear();
    air.Clipboard.generalClipboard.setData(air.ClipboardFormats.TEXT_FORMAT, text, false);
}

Skink.Sys.getFileContents = function(path) {
    var f = new air.File(path);
    if (f.exists) {
        var fs = new air.FileStream();
        fs.open(f, air.FileMode.READ);
        var str = fs.readMultiByte(f.size, air.File.systemCharset);
        fs.close();
        return str;
    } else {
        return false;
    }
};

/*
	@TODO: should really wrap the business end of this in a try/catch
*/
Skink.Sys.setFileContents = function(path, content, serialize) {
    if (serialize) {
        content = JSON.stringify(content);
    }

    Skink.dump('setFileContents for ' + path + ' to "' + content + '"');

    var f = new air.File(path);
    var fs = new air.FileStream();
    fs.open(f, air.FileMode.WRITE);
    fs.writeUTFBytes(content);
    fs.close();
};

Skink.Sys.openInBrowser = function(url) {
    Skink.dump('opening ' + url);
    var request = new air.URLRequest(url);
    try {
        air.navigateToURL(request);
    }
    catch(e) {
        Skink.dump(e.errorMsg)
    }
};

Skink.Sys.openAppStorageFolder = function() {
    Skink.Sys.openInBrowser('file://' + air.File.applicationStorageDirectory.nativePath);
};